#include "_alloc.h"
#include <stdint.h>

// 内存块头部结构
typedef struct BlockHeader {
    size_t size;              // 块的大小（不包括头部）
    struct BlockHeader* next; // 下一个块
    int free;                 // 是否空闲
} BlockHeader;

// 内存池
static uint8_t memory_pool[MEMORY_POOL_SIZE];
static BlockHeader* free_list = NULL;

// 对齐宏
#define ALIGN(size) (((size) + (MEMORY_POOL_ALIGNMENT - 1)) & ~(MEMORY_POOL_ALIGNMENT - 1))

static void memset(void* ptr, int value, size_t num) {
    for (size_t i = 0; i < num; i++) {
        ((uint8_t*)ptr)[i] = (uint8_t)value;
    }
}

// 内存池初始化函数（私有，自动调用）
static void memory_pool_init(void) {
    free_list = (BlockHeader*)memory_pool;
    free_list->size = MEMORY_POOL_SIZE - sizeof(BlockHeader);
    free_list->next = NULL;
    free_list->free = 1;
}

// 分割块
static void split_block(BlockHeader* block, size_t size) {
    BlockHeader* new_block = (BlockHeader*)((uint8_t*)block + sizeof(BlockHeader) + size);
    new_block->size = block->size - size - sizeof(BlockHeader);
    new_block->next = block->next;
    new_block->free = 1;
    
    block->size = size;
    block->next = new_block;
}

// 合并相邻的空闲块
static void merge_free_blocks(void) {
    BlockHeader* current = free_list;
    while (current && current->next) {
        if (current->free && current->next->free) {
            current->size += sizeof(BlockHeader) + current->next->size;
            current->next = current->next->next;
        } else {
            current = current->next;
        }
    }
}

// 自定义 malloc 实现
void* malloc_custom(size_t size) {
    if (free_list == NULL) {
        memory_pool_init(); // 自动初始化内存池
    }

    size = ALIGN(size);
    BlockHeader* current = free_list;
    
    while (current) {
        if (current->free && current->size >= size) {
            if (current->size > size + sizeof(BlockHeader)) {
                split_block(current, size);
            }
            current->free = 0;
            return (void*)((uint8_t*)current + sizeof(BlockHeader));
        }
        current = current->next;
    }
    // 内存不足
    return NULL;
}

// 自定义 calloc 实现
void* calloc_custom(size_t num, size_t size) {
    size_t total_size = num * size;
    void* ptr = malloc_custom(total_size);
    if (ptr) {
        memset(ptr, 0, total_size);
    }
    return ptr;
}

// 自定义 free 实现
void free_custom(void* ptr) {
    if (ptr == NULL) {
        return;
    }

    if (free_list == NULL) {
        memory_pool_init(); // 如果释放时内存池未初始化，则初始化（应避免这种情况）
    }
    
    BlockHeader* block = (BlockHeader*)((uint8_t*)ptr - sizeof(BlockHeader));
    block->free = 1;
    
    // 合并相邻的空闲块
    merge_free_blocks();
}
